package com.ruicar.afs.cloud.afscase.dispatch.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.afscase.dispatch.DispatchContext;
import com.ruicar.afs.cloud.afscase.dispatch.annotation.Dispatch;
import com.ruicar.afs.cloud.afscase.dispatch.enums.DispatchTypeEnum;
import com.ruicar.afs.cloud.afscase.dispatch.service.DispatchBaseServcie;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseBaseInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseCarInfoService;
import com.ruicar.afs.cloud.common.rules.RuleHelper;
import com.ruicar.afs.cloud.common.rules.constants.RuleRunEnum;
import com.ruicar.afs.cloud.common.rules.dto.RuleResult;
import com.ruicar.afs.cloud.common.rules.dto.RuleRunResult;
import com.ruicar.afs.cloud.seats.entity.RegularValue;
import com.ruicar.afs.cloud.seats.service.RegularValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author cheng.bi
 * 优先级
 */
@Service
@Dispatch(name = "优先级", dependsOn = "dispatchTopService", group = DispatchTypeEnum.CREDIT)
public class DispatchPriorService extends DispatchBaseServcie {


    @Autowired
    private CaseBaseInfoService caseBaseInfoService;
    @Autowired
    private CaseCarInfoService carInfoService;
    @Autowired
    private RegularValueService valueService;

    /**
     * 分单前实际处理方法
     *
     * @param context
     */
    public void process(DispatchContext context) {
        List<CaseBaseInfo> caseList = (List) (Optional.ofNullable(context.get(KEY)).orElse(new ArrayList()));
        caseList.stream().map(i -> {
            //调用优先级规则
            JSONObject jsonObject = (JSONObject) context.get(i.getId());
            RuleRunResult result = RuleHelper.runRule(jsonObject, "approvePriority", false, RuleRunEnum.SERIAL);
            List<Integer> rst = new ArrayList<>();
            if (result.getHit() == true) {
                List<RuleResult> resultList = result.getResults();
                for (RuleResult ruleResult : resultList) {
                    RegularValue regularValue = valueService.getById(ruleResult.getRuleNo());
                    if (ObjectUtil.isNotNull(regularValue)) {
                        rst.add(Integer.parseInt(regularValue.getValue()));
                    }
                }
                if (rst != null && !rst.isEmpty()) {
                    i.setPriority(String.valueOf(Collections.max(rst)));
                }
            }
            return i;
        }).collect(Collectors.toList());
        if (!caseList.isEmpty()) {
            caseBaseInfoService.updateBatchById(caseList);
        }
    }
}
